<template>
	<div class="flex_col card p10 m5">
		<label class="flex_center_self">串口设置</label>
		<div class="mt5 flex_row_center">
			<label>端口号</label>
			<el-select v-model="ctx.select_name" class="ml5" placeholder="端口选择" style="width: 120px;">
				<el-option v-for="(item, index) in ctx.names" :key="index" :label="item" :value="item" />
			</el-select>
		</div>
		<div class="flex_row_center mt5 flex_center_justify">
			<el-button @click="init" type="info">刷新</el-button>
			<el-button @click="onClickOpen" type="primary">{{ ctx.btn_text }}</el-button>
		</div>
	</div>
</template>

<script setup lang="ts">

import device from '../service/device/device.ts';
import { reactive } from 'vue'

interface Ctx {
	names: string[],
	select_name: string,
	btn_text: string,
}

const ctx = reactive<Ctx>({
	names: [],
	select_name: '',
	btn_text: '打开',
});

async function onClickOpen() {
	const ret = await device.serialPortIsOpen();
	if (!ret) {
		await device.serialPortOpen(ctx.select_name);
		ctx.btn_text = '关闭';
	} else {
		await device.serialPortClose();
		ctx.btn_text = '打开';
	}
}

async function update() {
	const ret = await device.serialPortIsOpen();
	if (ret) {
		ctx.btn_text = '关闭';
	} else {
		ctx.btn_text = '打开';
	}
}

async function init() {
	const names = await device.serialPortNames();
	ctx.names = names;
	if (names.length != 0) {
		ctx.select_name = names[0];
	}
	await update();
}

init();

</script>
